<template>
    <div class="store">

        <!-- 贴顶导航 -->
        <UserFixedHead title="Stores" />

        <!-- 初始化加载中 -->
        <UxIniting v-if="!inited" />

        <!-- 空页面 -->
        <StoreEmpty v-else-if="empty" />

        <!-- 有店铺 -->
        <template v-else>

            <UserFixedForm padding="0 180px" :top="216">
                <UserSearchName v-model="form.name" size="medium" shape="solid" placeholder="Store listing title"
                                @change="doSearch()" />
                <UserSearchButton size="medium" shape="text" name="New store" icon="user-template-new"
                                  @click="doNewStore()" />
                <UserSearchButton size="medium" shape="text" name="Add product" icon="user-template-new"
                                  v-if="store.shop_state != 2" @click="doAddProduct()" />
            </UserFixedForm>

            <h2>
                <strong>Stores</strong>
                <button @click="$router.push('/settings/store?id=' + store.id)" title="Store settings">
                    <svg-icon name="user-store-setting" />
                </button>
            </h2>

            <StoreList v-model="form.store_id" :stores="stores" @change="setStore()" ref="store-list" />

            <div class="order-subtitle">
                <StoreTabs v-model="form.status" :form="form" @change="doSearch()" />
                <UserSearchName v-model="form.name" size="large" shape="plain" placeholder="Store listing title"
                                @change="doSearch()" />
                <StoreAddProduct :store="store" :disabled="store.shop_state == 2" ref="add-product" />
            </div>

            <div class="order-match" v-show="searching">
                <span v-text="form.total"></span>
                <em v-if="form.total > 1"> matches found</em>
                <em v-else> match found</em>
            </div>

            <div class="table-title">
                <span>Product</span>
                <span>Variants</span>
                <span>
                    <em>Cost</em>
                    <UxToolTip content="Shipping and taxes excluded." placement="top" />
                </span>
                <span>Status</span>
                <span>Actions</span>
            </div>

            <template v-if="list.length == 0">
                <UxSearchEmpty v-if="searching" />
                <div class="table-empty" v-else>
                    <svg-icon name="user-shop" />
                    <p>You are one step closer to selling unique and cool products.</p>
                    <StoreAddProduct :store="store" />
                    <!-- <button @click="doAddProduct" v-loading="add_product_loading">Add product</button> -->
                </div>
            </template>

            <template v-else>

                <ul class="table-body">

                    <li v-for="item in list" :key="item.id"
                        :class="{ 'table-brand': item.tag_design_info || item.pack_design_info }">
                        <div class="table-model">
                            <CommonStoreTemplatePreview :item="item" />
                            <h3 v-text="item.title"></h3>
                        </div>

                        <div class="table-info" :suit="item.data.length > 1">
                            <div class="table-info-pro" v-for="product in item.data"
                                 :key="item.id + '-' + product.design_id + product.size_list.length">
                                <div class="table-info-select">
                                    <div class="table-info-title" v-text="product.sub_title"></div>
                                    <div class="table-info-color">
                                        <em v-for="color in product.color_list" :key="color.color_id"
                                            :style="{ backgroundColor: color.color_num }"></em>
                                    </div>

                                    <div class="table-info-size">
                                        <em v-if="product.size_list.length == 0"> -- </em>
                                        <em v-else-if="product.size_list.length == 1"
                                            v-text="product.size_list[0].size_name"></em>
                                        <em v-else
                                            v-text="product.size_list[0].size_name + '-' + product.size_list[product.size_list.length - 1].size_name"></em>
                                    </div>
                                </div>

                                <div class="table-info-cost">
                                    <CommonLevelDiscount v-if="product.low_price == product.high_price" :level="item"
                                                         :price="product.low_price + product.extra_price"
                                                         :blank="product.is_blank" type="unit|discount|icon" />
                                    <CommonLevelDiscount v-else :level="item"
                                                         :price="(product.low_price + product.extra_price) + '-' + (product.high_price + product.extra_price)"
                                                         :blank="product.is_blank" type="unit|discount|icon" />
                                </div>
                            </div>
                        </div>

                        <div class="table-async">
                            <!-- 同步状态 -->
                            <span v-if="item.status == 1">Synced</span>
                            <span v-if="item.status == 2">Synced failed</span>
                            <span v-if="item.status == 3">Draft</span>
                            <span v-if="item.status == 4">To be updated</span>
                            <span v-if="item.status == 5">Ignore</span>
                            <span v-if="item.status == 6">Synchronizing</span>
                        </div>

                        <StoreOperat :product="item" :stores="stores" :store="store" @getStatus="getStatus()"
                                     @update='getShopProductList' />

                        <CommonBrandPreview :tag="item.tag_design_info" :pack="item.pack_design_info" />

                        <UxLoadingInline :loading="item.status == 6 || item.loading" title="Synchronizing" />
                    </li>

                </ul>

                <!-- 分页 -->
                <CommonPage v-show="pageTotal > form.size" @current-change="changePage('num', $event)"
                            :current-page.sync="form.num" :page-size="form.size" :total.sync="pageTotal"></CommonPage>

            </template>

            <UxLoading2 :loading="loading" />

        </template>

    </div>
</template>
<script>
export default {
    name: "userStoreList",
    layout: "layout-user",
    data () {
        return {
            inited: false,
            loading: true, // 是否加载中
            empty: true,
            searching: false,
            polling: 0, // 状态轮询
            form: {
                name: '',
                store_id: 0,
                status: 0,
                num: 1,
                size: 10,
                total: 0,
                ignore_count: 0,
                synced_count: 0,
                draft_count: 0,
                sync_failed: 0,
                to_be_updated_count: 0,
            },
            stores: [],
            list: [],
        };
    },
    computed: {
        pageTotal () {
            let code = this.form.status || 0;
            let result = {
                0: this.form.total,
                1: this.form.synced_count,
                2: this.form.sync_failed,
                3: this.form.draft_count,
                4: this.form.to_be_updated_count,
                5: this.form.ignore_count,
            }[code];
            return result;
        },
        store: {
            get () {
                let store_id = this.form.store_id;
                let store = this.stores.filter(item => item.id == store_id)[0] || {};
                return store
            }
        }
    },
    methods: {

        // 获取商店列表
        async getStore () {
            let shop_id = (this.$route.query || {}).shop_id;
            let store_result = await this.$http("UserStore.getAllLinkStore");
            let stores = store_result.data || [];

            let store_ids = stores.map((i) => i.id);
            let store_id = store_ids.indexOf(shop_id) >= 0 ? shop_id : store_ids[0];


            if (store_result.code == 0 && stores.length > 0) {
                this.form.store_id = store_id || 0;
                this.stores = stores;
            }
        },


        // 商品列表分页等
        async getShopProductList () {
            if (this.form.store_id) {
                this.loading = true;
                const store_id = this.form.store_id;
                const request = {
                    page_num: this.form.num,
                    page_size: this.form.size,
                    status: this.form.status,
                    name: this.form.name
                };

                const response = await this.$http("UserStore.getShopProductListSuit/" + store_id, request);
                const data = response.data || {};

                this.loading = false;
                this.list = this.productDataFormat(data.product_info || []);

                this.form.total = data.total;
                this.form.ignore_count = data.ignore_count || 0;
                this.form.synced_count = data.synced_count || 0;
                this.form.draft_count = data.draft_count || 0;
                this.form.sync_failed = data.sync_failed || 0;
                this.form.to_be_updated_count = data.to_be_updated_count || 0;

                this.searching = !!request.name

                this.list.length > 0 && this.getStatus(); // 检查状态
                response.code != 0 && this.$uxMessage.error(response.msg || "error"); // 错误提示
            }

        },

        // 获取状态
        async getStatus () {

            let syncing = this.list.filter((i) => i.status == 6);
            let ids = syncing.map((i) => i.id);


            if (process.client && !this._isDestroyed && ids.length > 0 && /^\/user\/store\b/.test(location.pathname)) {
                let response = await this.$http("UserStore.getProductStatus", { id_list: JSON.stringify(ids) });
                if (response.code === 0) {
                    (response.data || []).map((item) => {
                        // 1 Synced
                        // 2 Sync failure
                        // 3 Draft
                        // 4 To be updated
                        // 5 Ignore
                        // 6 synchronizing

                        let syncobj = Object.fromEntries(syncing.map((item) => [item.id, item]));
                        let select = syncobj[item.id];
                        if (!item || !select) {
                            // 为空不管他
                        } else if (item.status == select.status) {
                            // 状态相同，不管他
                        } else {
                            if (item.status == 1) {
                                // 成功
                                let notify =
                                    select.status_cache == 2
                                        ? "Adding product to store successfully"
                                        : "Product synced successfully";
                                this.$uxMessage.success(notify);
                                select.status = item.status;
                                select.status_cache = item.status;
                                select.loading = false;

                                this.form.synced_count += 1;

                            } else if (item.status == 2) {
                                // 失败
                                this.$uxMessage.error("Failed to sync product");
                                select.status = item.status;
                                select.status_cache = item.status;
                                select.loading = false;
                                this.form.sync_failed += 1;
                            } else if (item.status == 3) {
                                // 存为草稿
                                this.$uxMessage.error("Failed to add to store and saved as draft");
                                select.status = item.status;
                                select.status_cache = item.status;
                            }
                        }
                    });
                }

                this.polling && clearTimeout(this.polling);
                this.polling = setTimeout(this.getStatus, 2000);
            }
        },

        // 数据格式化
        productDataFormat (list) {

            list.map((item) => {
                const custom = (item.data || []).filter(p => (p.design_info || []).filter(i => i.custom_count > 0).length);
                item.custom = custom.length > 0;
                item.store_id = this.form.store_id;
                item.img_url = item.img_url || '';
                item.status_cache = item.status; // 保存初始状态
                item.loading = false;
            });

            return list;
        },

        // 切换店铺
        setStore () {
            this.form.num = 1;
            this.form.name = '';
            this.form.status = 0;
            this.getShopProductList().then(() => window && window.scrollTo(0, 0));
        },

        // 搜索
        doSearch () {
            this.form.num = 1;
            this.getShopProductList().then(() => window && window.scrollTo(0, 0))
        },

        // 分页数据改变
        changePage: function (type, value) {
            this.form.num = value;
            this.getShopProductList().then(() => window && window.scrollTo(0, 0));
        },

        // 连接店铺
        doNewStore () {
            const handle = this.$refs['store-list']
            handle && (handle.dialog = true)
        },

        // 新产品
        doAddProduct () {
            const handle = this.$refs['add-product']
            handle && handle.doAddProduct()
        }

    },
    created () {
        if (process.client) {
            this.getStore().then(() => this.getShopProductList()).then(() => {
                this.inited = true
                this.empty = this.stores.length == 0
            })
        }

    },
    mounted () { },
};
</script>
<style lang="scss" scoped>
.store {
    display: flex;
    flex-direction: column;
    position: relative;

    &>.initing {
        flex: 1;
    }

    &>.loading {
        position: fixed;
        left: 228px;
        top: 0;
        bottom: 0;
        right: 0;
    }

    &>h2 {
        display: flex;
        align-items: center;
        font-size: 36px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 40px;

        strong {
            font-weight: 500;
        }

        button {
            margin-left: 10px;
            width: 28px;
            height: 28px;
            border-radius: 6px;
            padding: 0;
            border: 1px solid #e6e6e6;

            &:hover {
                background-color: #e6e6e6;
                color: #000;
            }
        }

        svg {
            width: 18px;
            height: 18px;
            box-sizing: border-box;
            cursor: pointer;
            color: #666;
        }
    }

    .user-fixed-form {
        .user-search-name {
            margin-right: 16px;
        }

        .user-search-button {
            width: auto;
            margin-left: 8px;
        }
    }

    &[fixed-form] .fixed-form {

        .user-search-name,
        .user-search-button {
            pointer-events: all;
        }
    }
}

.order-subtitle {
    display: flex;
    margin-top: 32px;
    margin-bottom: 32px;
    height: 36px;
    align-items: center;

    .store-status {
        flex: 1;
    }

    .user-search-name {
        height: 36px;
        width: 240px;
        flex: initial;
    }

    .store-add-product {
        width: 128px;
        height: 36px;
        margin-left: 6px;
    }
}

.order-match {
    font-size: 22px;
    font-family: Roboto-Medium, Roboto;
    font-weight: 500;
    color: #000000;
    line-height: 22px;
    margin-bottom: 20px;
}

.search-empty {
    margin-top: 12px;
}

.table-empty {
    margin-top: 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex: 1;
    height: 480px;
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #ebebeb;

    svg {
        width: 64px;
        height: 64px;
        color: #d8d8d8;
    }

    p {
        margin-top: 20px;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #9e9e9e;
        line-height: 20px;
    }

    .store-add-product {
        margin-top: 20px;
        width: 140px;
        height: 40px;
    }
}

.table-title {
    display: flex;
    position: relative;
    height: 40px;
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #e6e6e6;

    &>span {
        text-align: center;
        position: relative;
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #292929;
        white-space: nowrap;
        box-sizing: border-box;
        padding: 10px 18px;
        line-height: 20px;

        &:first-child {
            border-radius: 2px 0 0 2px;
        }

        &:last-child {
            border-radius: 0 2px 2px 0;
        }

        &:nth-child(1) {
            width: 18.7%;
        }

        &:nth-child(2) {
            width: 22.5%;
        }

        &:nth-child(3) {
            width: 20.4%;
        }

        &:nth-child(4) {
            width: 18.7%;
        }

        &:nth-child(5) {
            width: 19.7%;
        }

        .tooltip {
            margin-left: 2px;
            position: relative;
            top: -1px;
        }
    }
}

.table-body {
    &>li {
        display: flex;
        align-items: center;
        position: relative;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #ebebeb;
        margin-top: 12px;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;

        &.table-brand {
            padding-bottom: 40px;

            .brand-preview {
                opacity: 1;
                pointer-events: all;
            }
        }

        &>div {
            box-sizing: border-box;

            &:nth-child(1) {
                width: 18.7%;
            }

            &:nth-child(2) {
                width: 42.9%;
            }

            &:nth-child(3) {
                width: 18.7%;
            }

            &:nth-child(4) {
                width: 19.7%;
            }
        }

        .loading-inline {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(254, 255, 252, 0.9);
            border-radius: 8px;
        }
    }

    .table-model {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 18px;

        .store-preview {
            margin: 0 auto;
            width: 160px;
            height: 160px;
        }

        h3 {
            position: relative;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            /*! autoprefixer: off */
            -webkit-box-orient: vertical;

            margin: 8px auto 0;
            max-width: 160px;
            text-align: center;
            // word-break: break-word;
            word-break: break-all;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 18px;

        }
    }

    .table-info {
        flex-direction: column;
        align-items: center;

        .table-info-pro {
            display: flex;
            position: relative;
            align-items: center;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 16px;
            word-break: break-word;

            &+.table-info-pro::before {
                content: '';
                position: absolute;
                left: 24px;
                right: 24px;
                top: 0;
                height: 1px;
                background-color: #ebebeb;
            }
        }

        .table-info-select {
            width: 52.48%;
            padding: 12px 24px;
            box-sizing: border-box;
        }

        .table-info-cost {
            width: 48.52%;
            padding: 12px;
            box-sizing: border-box;
            display: flex;
            justify-content: center;
            align-items: center;

            .level-discount {
                font-size: 14px;
                justify-content: center;

                &[currency='JPY'] {
                    flex-wrap: wrap;

                    &::v-deep span {
                        margin: 0;

                        &[name='discount'] {
                            width: 100%;
                            margin: 4px;
                            text-align: center;
                        }
                    }
                }
            }
        }

        .table-info-title {
            display: none;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 16px;
            padding-bottom: 10px;
        }

        .table-info-color {
            position: relative;
            display: flex;
            flex-wrap: wrap;
            padding-left: 46px;
            padding-bottom: 10px;
            line-height: 16px;

            &::before {
                content: 'Color:';
                position: absolute;
                left: 0;
                top: 0;
            }

            &>em {
                margin: 2px;
                width: 12px;
                height: 12px;
                box-sizing: border-box;
                border-radius: 1px;
                border: 1px solid rgba(0, 0, 0, 0.16);
            }
        }

        .table-info-size {
            position: relative;
            display: flex;
            flex-wrap: wrap;
            padding-left: 48px;
            line-height: 16px;

            &::before {
                content: 'Size:';
                position: absolute;
                left: 0;
                top: 0;
            }

            &>em {
                line-height: 16px;
            }
        }

        // 套装
        &[suit] {
            .table-info-title {
                display: block;
            }

            .table-info-pro:first-child {
                padding-top: 20px;
            }

            .table-info-pro:last-child {
                padding-bottom: 20px;
            }
        }
    }

    .table-async {
        color: #000000;
        padding: 12px;
        text-align: center;
        height: 100%;
        font-size: 14px;
    }

    .brand-preview {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 40px;
        border-radius: 0 0 8px 8px;
        border-top: 1px solid #e5e5e5;
        opacity: 0;
        pointer-events: none;
    }
}

.common-page {
    padding: 24px 0 0;
    justify-content: flex-end;
}
</style>
